package net.ib.mtalk.ui;

import java.io.File;

import net.ib.mntalk.protocol.Common.AccessToken;
import net.ib.mntalk.protocol.Session.GetSvcAgreementReq;
import net.ib.mntalk.protocol.Session.GetSvcAgreementRes;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseTabActivity;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.ViewTable;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.NetFlowControl;
import net.ib.mtalk.network.task.GetSvcAgreementTask;
import net.ib.mtalk.sync.AsyncCheckVersion;
import net.ib.mtalk.ui.buddy.BuddyTabActivity;
import net.ib.mtalk.ui.community.CommunityListActivity;
import net.ib.mtalk.ui.favorite.FavoriteActivity;
import net.ib.mtalk.ui.inbox.InboxListActivity;
import net.ib.mtalk.ui.setting.SettingsActivity;
import net.ib.mtalk.ui.setting.about.SettingUsageMtalk;
import net.ib.mtalk.ui.start.ClauseActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Application 이 실행될 때 처음으로 실행되는 Activity 이다.
 * 
 * @author happy2v
 *
 */

public class HomeActivity extends BaseTabActivity {
	
	// 각 탭의 Indicator를 만들어주기 위한 구분 상수.
	private static Context mContext;
	
	private final int INDICATOR_FAVORITE 	= 0x00;
	private final int INDICATOR_BUDDY	 	= 0x01;
	private final int INDICATOR_CHATLIST 	= 0x02;
	private final int INDICATOR_COMMUNITY 	= 0x03;
	
	private static final String TAG_FAVORITE 	= "favorite";
    private static final String TAG_BUDDY		= "buddy";
    private static final String TAG_CHATLIST 	= "chatlist";
    private static final String TAG_COMMUNITY 	= "community";
    
   // private ProgressDialog mProgressDialog; 
    
    private TextView mIndoxBadge;
    private static TextView mTalkBadge;
    private ImageView mDoor;
    
    private Cursor mViewTableCursor;
	
    private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
				case HandlerMsgConst.HANDLER_AUTHENTICATE_SUCCESS:
					Toast.makeText(mContext, "HANDLER_AUTHENTICATE_SUCCESS", Toast.LENGTH_SHORT).show();
					//mProgressDialog.hide();
					mDoor.setVisibility(View.GONE);
					break;
				case HandlerMsgConst.HANDLER_AUTHENTICATE_FAIL :
					Toast.makeText(mContext, "HANDLER_AUTHENTICATE_FAIL", Toast.LENGTH_SHORT).show();
					//mProgressDialog.hide();
					startActivity(new Intent(mContext, ClauseActivity.class));
					//finish();
					break;
				case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
					Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
					//mProgressDialog.hide();
					mDoor.setVisibility(View.GONE);
					//finish();
					break;
				case HandlerMsgConst.HANDLER_GET_SVC_AGREEMENT_SUCCESS:
					Toast.makeText(mContext, "HANDLER_GET_SVC_AGREEMENT_SUCCESS", Toast.LENGTH_SHORT).show();
					GetSvcAgreementRes getSvcAgreementRes = (GetSvcAgreementRes)msg.obj;
					if(getSvcAgreementRes.getVersion() == GlobalPreferences.getSvcVersion())
						checkAuth();
					else
					{
						String str = "getSvcAgreementRes.getVersion() = " + getSvcAgreementRes.getVersion() + ", GlobalPreferences.getSvcVersion() = " + GlobalPreferences.getSvcVersion();
						Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
						
						Intent intent = new Intent(mContext, ClauseActivity.class);
						intent.putExtra("changeVersion", true);
						startActivity(intent);
						finish();
					}
					break;
				case HandlerMsgConst.HANDLER_GET_SVC_AGREEMENT_FAIL:
					Toast.makeText(mContext, "HANDLER_GET_SVC_AGREEMENT_FAIL", Toast.LENGTH_SHORT).show();
					mDoor.setVisibility(View.GONE);
					break;
				default:
					break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		mContext = this;
		
		if(getIntent().getBooleanExtra("usage", false))
		{
			startActivity(new Intent(mContext, SettingUsageMtalk.class));
		}
		
		mDoor = (ImageView)findViewById(R.id.door);
		if(!NetFlowControl.checkNetWorkStatus(mContext))
		{
			AlertDialog dialog = new AlertDialog.Builder(mContext).setMessage(getString(R.string.network_connect_msg))
			.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					mDoor.setVisibility(View.GONE);
					dialog.dismiss();
				}
			}).create();
			dialog.setCancelable(false);
			dialog.show();
		}
		else if(!hasAccessToken())
		{
			Log.e("test", "HomeActivity.checkAuth() : has no accessToken");
			startActivity(new Intent(this, ClauseActivity.class));
			finish();
			return;
		}
		getSvcAgreement();
//		if(!checkAuth())
//			return;
		
		SettingsActivity.setDefaultSettingPref();
		
		final TabHost host = getTabHost();
		
		// 각 탭의 내부 인텐트
		final Intent intentFavorite = new Intent(this, FavoriteActivity.class);
		intentFavorite.addCategory(Intent.CATEGORY_TAB);
		final Intent intentBuddy = new Intent(this, BuddyTabActivity.class);
		intentBuddy.addCategory(Intent.CATEGORY_TAB);
		final Intent intentChatlist = new Intent(this, InboxListActivity.class);
		intentChatlist.addCategory(Intent.CATEGORY_TAB);
		final Intent intentCommunity = new Intent(this, CommunityListActivity.class);
		intentCommunity.addCategory(Intent.CATEGORY_TAB);
	    
		// 탭을 만들어 준다.
		host.addTab(host.newTabSpec(TAG_FAVORITE)
                .setIndicator(buildIndicator(INDICATOR_FAVORITE))
                .setContent(intentFavorite));
		host.addTab(host.newTabSpec(TAG_BUDDY)
				.setIndicator(buildIndicator(INDICATOR_BUDDY))
                .setContent(intentBuddy));
		host.addTab(host.newTabSpec(TAG_CHATLIST)
				.setIndicator(buildIndicator(INDICATOR_CHATLIST))
                .setContent(intentChatlist));
/*		
 * 	v2.1 에서 추가
		host.addTab(host.newTabSpec(TAG_COMMUNITY)
				.setIndicator(buildIndicator(INDICATOR_COMMUNITY))
                .setContent(intentCommunity));
*/
		selectNewBuddy();
		
		// Contact 변화 검사 
		AsyncCheckVersion versionCheck = new AsyncCheckVersion();
		versionCheck.execute();
		
		makeDefaultFolder();
	}
	
	private void getSvcAgreement()
	{
		GetSvcAgreementReq getSvcAgreementReq = new GetSvcAgreementReq();
		getSvcAgreementReq.setUserUuid(GlobalPreferences.getUserUUID());
		
		GetSvcAgreementTask task = new GetSvcAgreementTask(mContext, mHandler, getSvcAgreementReq);
		task.execute();
		
		mDoor.setVisibility(View.VISIBLE);
	}
	
	public static void makeDefaultFolder()
	{
		File dirPath = new File(MTalkConstant.MTALK_PATH);
		if(!dirPath.exists())
		{
			if(!dirPath.mkdir())
			{
				new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android").mkdir();
				new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data").mkdir();
				dirPath.mkdir();
			}
		}
	}
	
	public static void selectNewBuddy() {
		Cursor cursor = mContext.getContentResolver().query(BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, 
				BuddyTable.KEY_BUDDY_NEW_FRIEND + "=1 AND " + BuddyTable.KEY_BUDDY_STATUS_TYPE + "=1", null, null);
		try{
			if(cursor != null){
				if(cursor.getCount() > 0){
					updateTalkBadge(true);
				} else {
					updateTalkBadge(false);
				}
			}
		} finally{
			cursor.close();
		}
	}

	public void updateInboxBadge(int count)
	{
		if(count > 0)
		{
			mIndoxBadge.setVisibility(View.VISIBLE);
			mIndoxBadge.setText(String.valueOf(count));
		}
		else
			mIndoxBadge.setVisibility(View.GONE);
		
	}

	public static void updateTalkBadge(boolean newBuddy)
	{
		if(newBuddy)
		{
			mTalkBadge.setVisibility(View.VISIBLE);
		}
		else
			mTalkBadge.setVisibility(View.GONE);
		
	}
	
	public void onDestroy()
	{
//		if(mProgressDialog != null)
//			mProgressDialog.dismiss();
		super.onDestroy();
	}
	
	public void onResume()
	{
		super.onResume();
		//checkAuth();
		registerViewTableObserver();
		mViewTableObserver.onChange(true);
	}
	
	protected void onStop() {
		super.onStop();
		unregisterViewTableObserver();
	}
	
	private void registerViewTableObserver()
	{
		getContentResolver().registerContentObserver(ViewTable.CONTENT_URI, true, mViewTableObserver);
	}
	
	private void unregisterViewTableObserver()
	{
		getContentResolver().unregisterContentObserver(mViewTableObserver);
		if(mViewTableCursor != null)
			mViewTableCursor.close();
	}
	
	private boolean hasAccessToken()
	{
		AccessToken token = GlobalPreferences.getMessageFromPreferences(AccessToken.class);
		if(token == null)
			return false;
		
		return true;
	}
	
	private void checkAuth()
	{
		if(NetFlowControl.hasAuth()) {
			Log.e("test", "HomeActivity.checkAuth() : has auth");
			mDoor.setVisibility(View.GONE);
			return;
		}
		else
		{
			Log.e("test", "HomeActivity.checkAuth() : execute auth task");
			if(!NetFlowControl.tryGetAuth(this, mHandler)) {
				mDoor.setVisibility(View.GONE);
			}
		}
	}
	
	@Override
	protected void onStart() {
		super.onStart();
	}
    
	/**
	 * 탭의 Indicator를 만들어 뷰를 리턴한다.
	 * @param tabKind
	 * @return View 만들어진 indicator 뷰를 리턴한다.
	 */
    private View buildIndicator(int tabKind) {
        final RelativeLayout indicator = (RelativeLayout) getLayoutInflater().inflate(R.layout.tab_indicator_home,
                getTabWidget(), false);
        switch(tabKind){
        case INDICATOR_FAVORITE:        	
        	indicator.findViewById(R.id.tab_icon)
        	.setBackgroundResource(R.drawable.menu_add);
//        	((TextView)indicator.findViewById(R.id.tab_badge)).setText("9");
        	mTalkBadge = (TextView)indicator.findViewById(R.id.badge);
        	mTalkBadge.setVisibility(View.GONE);
        	break;
        case INDICATOR_BUDDY:
        	indicator.findViewById(R.id.tab_icon)
        	.setBackgroundResource(R.drawable.menu_friends);
//        	((TextView)indicator.findViewById(R.id.tab_badge)).setText("9");
        	mTalkBadge = (TextView)indicator.findViewById(R.id.badge);
        	mTalkBadge.setText("N");
        	break;
        case INDICATOR_CHATLIST:
        	indicator.findViewById(R.id.tab_icon)
        	.setBackgroundResource(R.drawable.menu_talk);
//        	((TextView)indicator.findViewById(R.id.tab_badge)).setText("9");
        	mIndoxBadge = (TextView)indicator.findViewById(R.id.badge);
        	break;
        case INDICATOR_COMMUNITY:
        	indicator.findViewById(R.id.tab_icon)
        	.setBackgroundResource(R.drawable.community_icon);
//        	((TextView)indicator.findViewById(R.id.tab_badge)).setText("9");
        	break;
        default:
        	indicator.findViewById(R.id.tab_icon)
        	.setBackgroundResource(R.drawable.tab_favorite_icon);
//        	((TextView)indicator.findViewById(R.id.tab_badge)).setText("9");
        }
        
        return indicator;
    }
    
    private ContentObserver mViewTableObserver = new ContentObserver(new Handler()) {
		public void onChange(boolean selfChange) {
			int count = 0;
			String[] select = {ViewTable.KEY_VIEW_UNREAD_COUNT};
			mViewTableCursor = getContentResolver().query(ViewTable.CONTENT_URI, select, null, null, null);
			if(mViewTableCursor != null)
			{
				mViewTableCursor.moveToFirst();
				for(int i = 0 ; i < mViewTableCursor.getCount() ; i++)
				{
					count += mViewTableCursor.getInt(mViewTableCursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_UNREAD_COUNT));
					mViewTableCursor.moveToNext();
				}
				
				updateInboxBadge(count);
			}
		};
	};
}